package cn.tongji.edu.tjmobile;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static cn.tongji.edu.tjmobile.R.*;

public class StartCampusSelectionActivity extends Activity {

    private List<View> componentList = new ArrayList<>();
    private JSONArray busArray;
    private String campus;
    private String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layout.activity_start_campus_selection);

        TextView nextStepView = (TextView) findViewById(id.next_step_view);
        nextStepView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    for(int i = 0;i != componentList.size();i++){
                        if(isStartCampusSelected(componentList.get(i))){
                            TextView textView = (TextView) componentList.get(i).findViewById(id.start_campus_textview);
                            campus = textView.getText().toString();
                            System.out.print(campus);
                        }
                    }

                    ArrayList<String> endList = new ArrayList<String>();
                    for(int i = 0;i != busArray.length();i++){
                        String startCampus = ((JSONObject)busArray.get(i)).getString("start");
                        if(startCampus.equals(campus)){
                            String endCampus = ((JSONObject)busArray.get(i)).getString("end");
                            endList.add(endCampus);
                        }
                    }

                    Intent intent = new Intent();
                    intent.putExtra("startCampus", campus);
                    intent.putStringArrayListExtra("endCampusOptions", endList);
                    intent.putExtra("json", content);
                    intent.setClass(StartCampusSelectionActivity.this, EndCampusSelectionActivity.class);
                    startActivity(intent);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        ImageView icBackView = (ImageView) findViewById(id.image_ic_back);
        icBackView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread () {
                    public void run () {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });

        GetBusListTask task = new GetBusListTask();
        task.execute();
    }

    private void setStartCampusSelected(View component) {
        RelativeLayout itemLayout = (RelativeLayout) component.findViewById(id.item_layout);
        TextView startCampusTextView = (TextView) component.findViewById(id.start_campus_textview);
        startCampusTextView.setTextColor(Color.parseColor("#fffa9d4c"));
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View imageLayout = inflater.inflate(layout.component_selected_image_layout, null);
        itemLayout.addView(imageLayout);
    }

    private void removeStartCampusSelected(View component) {
        RelativeLayout itemLayout = (RelativeLayout) component.findViewById(id.item_layout);
        TextView startCampusTextView = (TextView) component.findViewById(id.start_campus_textview);
        startCampusTextView.setTextColor(Color.parseColor("#ff000000"));
        itemLayout.removeViewAt(1);
    }

    private boolean isStartCampusSelected(View component) {
        TextView startCampusTextView = (TextView) component.findViewById(id.start_campus_textview);
        int color = startCampusTextView.getCurrentTextColor();
        if(color == -352948){
            return true;
        }
        return false;
    }

    class GetBusListTask extends AsyncTask<Integer, Integer, String> {

        @Override
        protected String doInBackground(Integer... params) {
            HttpClient client = new DefaultHttpClient();
            String url = "http://jiading.tongji.edu.cn:8080/TJbus2/BusServlet";
            HttpGet request = new HttpGet(url);
            try {
                HttpResponse response = client.execute(request);
                content = IOUtils.toString(response.getEntity().getContent());
                response.getEntity().consumeContent();
                Log.i("StartCampusSelectionActivity", content);
                busArray = new JSONArray(content);

                Set<String> startCampusNameSet = new HashSet<>();
                for(int i = 0;i != busArray.length();i++){
                    String startCampus = ((JSONObject)busArray.get(i)).getString("start");
                    if(!startCampusNameSet.contains(startCampus)){
                        startCampusNameSet.add(startCampus);
                    }
                }

                LinearLayout containerLayout = (LinearLayout) findViewById(id.start_campus_container_layout);

                LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                int count = 1;
                for(String startCampus : startCampusNameSet){

                    final View component = inflater.inflate(R.layout.component_start_campus_layout, null);
                    TextView startCampusTextView = (TextView) component.findViewById(id.start_campus_textview);
                    startCampusTextView.setText(startCampus);
                    containerLayout.addView(component);
                    if(count == 1){
                        setStartCampusSelected(component);
                    }
                    count++;
                    componentList.add(component);
                    component.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(!isStartCampusSelected(component)){
                                setStartCampusSelected(component);
                            }
                            for(int i = 0;i != componentList.size(); i++){
                                if(isStartCampusSelected(componentList.get(i)) && !component.equals(componentList.get(i))){
                                    removeStartCampusSelected(componentList.get(i));
                                }
                            }
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {

            }

            return null;
        }
    }
}
